package com.woniu.controller.operation;

import com.baidubce.http.ApiExplorerClient;
import com.baidubce.http.HttpMethodName;
import com.baidubce.model.ApiExplorerRequest;
import com.baidubce.model.ApiExplorerResponse;
import com.woniu.controller.BaseController;
import com.woniu.entity.Result;
import com.woniu.utils.QiNiuUpload;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/numRecognition")
@Api(tags = "图像识别")
public class ImageRecognitionController extends BaseController {

    /**
     * 传入车牌照片，生成车牌号码，车牌颜色等信息响应回去
     * */
    @ApiOperation("车牌识别")
    @PostMapping ("/")
    public String numRecognition(@RequestPart MultipartFile file) throws IOException {
        //七牛云上传图片过程
        String originalFilename = file.getOriginalFilename();
        String uuid = UUID.randomUUID().toString();
        String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
        String newName = uuid + substring;
        newName = newName.replace("-","");
        QiNiuUpload.uploadImage(file.getBytes(),newName);

        //车牌识别过程
        String path = "https://aip.baidubce.com/rest/2.0/ocr/v1/license_plate";
        ApiExplorerRequest request = new ApiExplorerRequest(HttpMethodName.POST, path);
        // 设置header参数  默认
        request.addHeaderParameter("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
        // 设置query参数  设置自己的access_token
        request.addQueryParameter("access_token", "24.7751e688d8321656504c067c3a69495c.2592000.1674632096.282335-29311661");
        // 设置jsonBody参数, 拼接图片地址
        String jsonBody = "url=http://rnhimnldn.hd-bkt.clouddn.com/" + newName;
        request.setJsonBody(jsonBody);
        ApiExplorerClient client = new ApiExplorerClient();
        //定义返回变量
        String result = "";
        try {
            ApiExplorerResponse response = client.sendRequest(request);
            // 返回结果格式为Json字符串
            System.out.println(response.getResult());
            result = response.getResult();
        } catch (Exception e) {
            e.printStackTrace();
        }
        //操作字符串，给返回的json加上图片名
        //去除字符串第一位
        result = result.substring(1);
        result = "{\"imageUrl\":\"" + newName + "\"," + result;
        return result;
    }
}
